using System;
using System.Xml;
using DesignByContract;
using Outcoding.GraphGenerator.Entities;
using Outcoding.GraphGenerator.Util.Logging;

namespace Outcoding.GraphGenerator.Composition{
    public class SeriesBuilder : BuilderBase{
        #region Attributes

        /*  Table Cell dimensions   */
        private readonly string cellHeightAttr = "cell-height";
        private readonly string cellWidthAttr = "cell-width";

        #endregion

        private readonly string mNodeName = XmlTagNames.series.ToString();

        private XmlNode mNode;

        private string mNodePath{
            get { return "./" + mNodeName; }
        }

        public override void SelectNode(XmlDocument document){
            throw new Exception("The method or operation is not implemented.");
        }

        public override void Compose(){
            throw new Exception("The method or operation is not implemented.");
        }

        public override void Compose(XmlNode node){
            mNode = node; //.SelectSingleNode(mNodePath);
            try{
                BuildObject(mNode);
            }
            catch (PreconditionException preExc){
                LogManager.Instance.LogWarning("Series entity could not be created; process aborted.", preExc);
            }
        }

        public override void AppendToParent(object parent){
            Check.Require(parent is SeriesCollection, "Parent object not a valid argument");
            (parent as SeriesCollection).Add((Series) mProduct);
        }

        private void BuildObject(XmlNode axesXmlNode){
            var series = new Series();

            try{
                //Table dimension attributes
                if (axesXmlNode.Attributes[cellHeightAttr] != null)
                    series.CellHeight = ParseCellHeightAttribute(axesXmlNode);
                if (axesXmlNode.Attributes[cellWidthAttr] != null)
                    series.CellWidth = ParseCellWidthAttribute(axesXmlNode);
            }
            catch (PreconditionException preExc){
                //log error
                series = null;
                throw;
            }

            mProduct = series;
        }


        private int ParseCellHeightAttribute(XmlNode majorGridlineXmlNode){
            Check.Require(majorGridlineXmlNode.Attributes[cellHeightAttr] != null, "cell-height attribute not present");

            return Int32.Parse(majorGridlineXmlNode.Attributes[cellHeightAttr].Value);
        }

        private int ParseCellWidthAttribute(XmlNode majorGridlineXmlNode){
            Check.Require(majorGridlineXmlNode.Attributes[cellWidthAttr] != null, "cell-width attribute not present");

            return Int32.Parse(majorGridlineXmlNode.Attributes[cellWidthAttr].Value);
        }
    }
}